package com.situ.mall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.situ.mall.api.ProductClient;
import com.situ.mall.common.util.Result;
import com.situ.mall.order.entity.vo.CartVO;
import com.situ.mall.pojo.entity.order.Cart;
import com.situ.mall.order.mapper.CartMapper;
import com.situ.mall.order.service.ICartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.mall.pojo.entity.product.Product;
import com.situ.mall.product.mapper.ProductMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author Z
 * @since 2024-10-14
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductClient productClient;
    @Override
    public CartVO add(Cart cart) {
        //加入到数据库
        cartMapper.insert(cart);

        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",cart.getId());
        Cart selectOne = cartMapper.selectOne(queryWrapper);
        CartVO cartVO = new CartVO();
        BeanUtils.copyProperties(selectOne,cartVO);

        Result<Product> result = productClient.getById(cart.getProductId());
        if (result.getCode()==0){
            Product product = result.getData();
            cartVO.setProductName(product.getName());
            cartVO.setProductPrice(product.getPrice());
            cartVO.setProductImage(product.getImage());

        }
        return cartVO;
    }

    @Override
    public List<CartVO> selectByUserId(Long id) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        List<Cart> cartList = cartMapper.selectList(queryWrapper);

        List<CartVO> cartVOList = new ArrayList<>();
        for (Cart cart : cartList) {
            CartVO cartVO = new CartVO();
            BeanUtils.copyProperties(cart, cartVO);
            Result<Product> result = productClient.getById(cart.getProductId());
            if (result.getCode() == 0) {
                Product product = result.getData();
                cartVO.setProductImage(product.getImage());
                cartVO.setProductName(product.getName());
                cartVO.setProductPrice(product.getPrice());
            }

            cartVOList.add(cartVO);
        }

        return cartVOList;
    }

    @Override
    public void updateCheckedAll(Cart cart) {
        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("checked", cart.getChecked());
        cartMapper.update(null, updateWrapper);
    }
}
